package com.zhousb.deviceManager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhousb.deviceManager.mapper.SysTenantMapper;
import com.zhousb.deviceManager.model.entity.SysTenant;
import com.zhousb.deviceManager.model.so.SimpleSo;
import com.zhousb.deviceManager.service.SysTenantService;
import com.zhousb.deviceManager.utils.AuthUtils;
import com.zhousb.deviceManager.utils.IdGenerator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author ZhouShenBin
 * @date 2024/3/14 14:14
 * @description
 */

@Service
public class SysTenantServiceImpl implements SysTenantService {

    @Resource
    private SysTenantMapper sysTenantMapper;
    @Resource
    AuthUtils authUtils;

    @Override
    public Page<SysTenant> pageTenant(Page<SysTenant> page, SimpleSo so) {
        return sysTenantMapper.selectPage(page, null);
    }

    @Override
    public boolean createTenant(SysTenant sysTenant) {
        sysTenant.setId(IdGenerator.nextId());
        return sysTenantMapper.insert(sysTenant) > 0;
    }

    @Override
    public boolean editTenant(SysTenant sysTenant) {
        SysTenant tenant = sysTenantMapper.selectById(sysTenant.getId());
        if (Objects.isNull(tenant)) {
            throw new RuntimeException("租户不存在");
        }
        return sysTenantMapper.updateById(sysTenant) > 0;
    }

    @Override
    public List<SysTenant> listTenant() {
        boolean isSuperAdmin = authUtils.isSuperAdmin();
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!isSuperAdmin, SysTenant::getId, authUtils.getUser().getTenantId());
        return sysTenantMapper.selectList(queryWrapper);
    }
}
